package com.edu.whty.controller;

import com.edu.whty.common.constants.CodeConstants;
import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.*;
import com.edu.whty.entity.base.ResponseEntity;
import com.edu.whty.entity.cloud.Chapter;
import com.edu.whty.entity.cloud.ChapterVo;
import com.edu.whty.entity.usertextbook.UserTextBook;
import com.edu.whty.service.UserTextBookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/userTextBook")
public class UserTextBookController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserTextBookService userTextBookService;

    private static String CMS_SYN = "1";

    @RequestMapping(value = "/listUserTextBook", method = RequestMethod.POST)
    public ResponseEntity listUserTextBook(HttpServletRequest request, HttpServletResponse response, @RequestBody UserTextBook userTextBook) {
        try {
            List<UserTextBook> userTextBookList = userTextBookService.listUserTextBookByUserId(userTextBook);

            return ResponseEntity.getSuccessResponse(userTextBookList);
        } catch (Exception e) {
            logger.error("获取教材列表异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, e.getMessage());
        }
    }

    @RequestMapping(value = "/saveUserTextBook", method = RequestMethod.POST)
    public ResponseEntity saveUserTextBook(HttpServletRequest request, HttpServletResponse response, @RequestBody UserTextBook userTextBook) {
        try {
            if (StringUtils.isEmpty(userTextBook.getUserId())
                    || StringUtils.isEmpty(userTextBook.getUserName())) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userId和userName不能为空");
            }

            if (StringUtils.isEmpty(userTextBook.getTextbookId())
                    || StringUtils.isEmpty(userTextBook.getTextbookName())) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "TextbookId和textbookName不能为空");
            }

            if (StringUtils.isEmpty(userTextBook.getPeriodId())
                    || StringUtils.isEmpty(userTextBook.getPeriodName())) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "periodId和periodName不能为空");
            }

            if (StringUtils.isEmpty(userTextBook.getSubjectId())
                    || StringUtils.isEmpty(userTextBook.getSubjectName())) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "subjectId和subjectName不能为空");
            }

            if (StringUtils.isEmpty(userTextBook.getOrgId())) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "orgId不能为空");
            }

            String netIp = null == request.getAttribute("netIp") ? null : request.getAttribute("netIp").toString();
            if (userTextBookService.isAdd(userTextBook)) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "您已经添加过该教材");
            } else {
                UserTextBook book = userTextBookService.saveTextBook(userTextBook);
                String query_chapters = SysConfig.getStrValue(TeaHelpUtils.QUERY_CHAPTERS);
                query_chapters = CmsOpenApiUtil.getTokenUrl(query_chapters, "/cms-gateway/queryChapters", Constant.PLATFORM_CODE_DEFAULT, netIp);
                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("userId", userTextBook.getUserId());
                paramMap.put("textbookId", userTextBook.getTextbookId());
                paramMap.put("loginPlatformCode", userTextBook.getLoginPlatformCode());
                paramMap.put("query_chapters", query_chapters);
                String cms_batchCreateFolder = SysConfig.getStrValue("cms_batchCreateFolder");
                cms_batchCreateFolder = CmsOpenApiUtil.getTokenUrl(cms_batchCreateFolder, "/cms-gateway/batchCreateFolder",
                        (String) SysConfig.getStrValue("loginPlatformCode"), netIp);
                paramMap.put("cms_batchCreateFolder", cms_batchCreateFolder);
                String cms_createFolder = SysConfig.getStrValue("cms_createFolder");
                cms_createFolder = CmsOpenApiUtil.getTokenUrl(cms_createFolder, "/cms-gateway/createFolder",
                        (String) SysConfig.getStrValue("loginPlatformCode"), netIp);
                paramMap.put("cms_createFolder", cms_createFolder);
                if (CMS_SYN.equals(SysConfig.getStrValue("cms_syn"))) {
                    ThreadPool.getIstance().execute(new Thread(new CreateCmsFolderThread(paramMap, book)));
                    ;
                }

                return ResponseEntity.getSuccessResponse(book);
            }

        } catch (Exception e) {
            logger.error("保存我的教材异常" + e.getMessage());
            // 捕捉异常构造返回信息
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "保存我的教材异常");
        }
    }

    @RequestMapping(value = "/delUserTextBook", method = RequestMethod.POST)
    public ResponseEntity delUserTextBook(HttpServletRequest request, HttpServletResponse response, @RequestBody UserTextBook userTextBook) {
        try {
            if (StringUtils.isEmpty(userTextBook.getId())) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "id不能为空");
            }

            UserTextBook ub = userTextBookService.loadUserTextBook(userTextBook.getId());

            //删除用户上次选择的教材章节缓存
            String cachedKey = userTextBook.getPlatformCode() + "_" + ub.getUserId();
            String cacheChapterKey = cachedKey + "_" + ub.getTextbookId();
            //删除用户教材
            userTextBookService.delteTextBookById(userTextBook.getId());
            return ResponseEntity.getSuccessResponse();
        } catch (Exception e) {
            logger.error("删除我的教材异常" + e.getMessage());
            // 捕捉异常构造返回信息
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "删除我的教材异常");
        }
    }

    /**
     * 查询章节信息
     * @param query
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/queryChapters", method=RequestMethod.POST)
    @ResponseBody
    public ResponseMessage queryChapters(@RequestBody ChapterVo query)
            throws Exception {
        String parentId = query.getParentId();
        String parentType = query.getParentType();
        String retType = query.getRetType();

        List<Chapter> chapterList = CollectionUtils.newArrayList();

        if (org.apache.commons.lang.StringUtils.isNotEmpty(parentId)) {
            Chapter model = new Chapter();
            model.setStatus("0");
            if ("0".equals(parentType)) { // 根据教材ID查章节
                model.setTextbookId(parentId);
                model.setChapterPid("0");
            } else if ("1".equals(parentType)) { // 根据上级章节ID查章节
                model.setChapterPid(parentId);
            } else {
                ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
                responseMessage.setResultDesc("parentType参数不正确");
                return responseMessage;
            }

            if ("0".equals(retType)) { // 返回整棵子树
                chapterList = userTextBookService.selectSubTreeList(model);
            } else if ("1".equals(retType)) { // 返回下级节点list
            } else {
                ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
                responseMessage.setResultDesc("retType参数不正确");
                return responseMessage;
            }
        }
        Map<String,Object> data = MapUtils.newHashMap();
        data.put("list", chapterList);
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        responseMessage.setData(data);
        return responseMessage;
    }
}
